from rest_framework import serializers
from user import models
import re


def checkemail(val):
    if not re.match(r'^[a-zA-Z0-9_]+@(163|139|sina|qq)\.com$', val):
        raise serializers.ValidationError('邮箱不合规')


def checkphone(val):
    if not re.match(r'^1[3-9]\d{9}$', val):
        raise serializers.ValidationError('手机号已经存在')


def checkusername(val):
    obj = models.User.objects.filter(username=val).first()
    if obj:
        raise serializers.ValidationError('用户名已经存在')


class SerUser(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = '__all__'

        extra_kwargs = {
            'email': {
                'error_messages': {
                    'required': '不能为空'
                },
                'validators': [checkemail]
            },
            'phone': {
                'error_messages': {
                    'required': '不能为空'
                },
                'validators': [checkphone]
            },
            'username': {
                'error_messages': {
                    'required': '不能为空'
                },
                'validators': [checkusername]
            }
        }

